<template>
	<view class="container">
		<!-- 需要生成图片的内容区域 -->
		<view id="shareCare" class="shareCare">
			<view class="careImg">
				<image :src="imageBaseUrl + '/post/static/5.png'" mode="aspectFit"></image>
			</view>
			<view class="careCon">
				<!-- 原有结构保持不变 -->
			</view>
		</view>

		<!-- 隐藏的画布 -->
		<canvas v-if="isMpWeixin" id="shareCanvas" type="2d" :style="{ position: 'absolute', left: '-9999px', width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>

		<button class="save-btn" @click="saveToImage" :disabled="isGenerating">
			{{ isGenerating ? '生成中...' : '保存为图片' }}
		</button>
	</view>
</template>

<script setup>
	import { ref, getCurrentInstance, onReady } from 'vue'
	import html2canvas from 'html2canvas' // H5端需要

	const instance = getCurrentInstance()
	const isMpWeixin = ref(process.env.VUE_APP_PLATFORM === 'mp-weixin')
	const isGenerating = ref(false)
	const canvasWidth = ref(300)
	const canvasHeight = ref(500)
	const imageBaseUrl = ref('https://your-cdn-domain.com') // 修改为实际CDN地址

	// 获取系统信息（小程序专用）
	const systemInfo = ref({})
	if (isMpWeixin.value) {
		onReady(async () => {
			systemInfo.value = await uni.getSystemInfoSync()
		})
	}

	async function saveToImage() {
		if (isGenerating.value) return
		isGenerating.value = true

		try {
			// #ifdef H5
			await generateH5Image()
			// #endif

			// #ifdef MP-WEIXIN
			await generateMpImage()
			// #endif
		} catch (e) {
			console.error('生成失败:', e)
			uni.showToast({ title: '生成失败，请重试', icon: 'none' })
		} finally {
			isGenerating.value = false
		}
	}

	// H5生成逻辑
	async function generateH5Image() {
		const element = document.getElementById('shareCare')
		const canvas = await html2canvas(element, {
			useCORS: true,
			scale: 2,
			backgroundColor: null
		})

		const imgData = canvas.toDataURL('image/png')
		const link = document.createElement('a')
		link.download = 'share.png'
		link.href = imgData
		link.click()
	}

	// 小程序生成逻辑
	async function generateMpImage() {
		const rect = await getElementRect('#shareCare')
		const dpr = systemInfo.value.pixelRatio || 1

		const ctx = uni.createCanvasContext('shareCanvas', instance)

		// 设置画布尺寸
		canvasWidth.value = rect.width * dpr
		canvasHeight.value = rect.height * dpr
		ctx.scale(dpr, dpr)

		// 绘制背景
		ctx.setFillStyle('#ffffff')
		ctx.fillRect(0, 0, rect.width, rect.height)

		// 递归绘制子元素
		await drawElement(ctx, '#shareCare', 0, 0)

		// 生成图片
		const tempPath = await new Promise((resolve, reject) => {
			ctx.draw(false, () => {
				uni.canvasToTempFilePath(
					{
						canvasId: 'shareCanvas',
						success: resolve,
						fail: reject
					},
					instance
				)
			})
		})

		// 保存到相册
		await checkPhotoPermission()
		await uni.saveImageToPhotosAlbum({
			filePath: tempPath.tempFilePath
		})
		uni.showToast({ title: '保存成功' })
	}

	// 通用工具方法
	async function getElementRect(selector) {
		return new Promise((resolve) => {
			uni.createSelectorQuery().in(instance).select(selector).boundingClientRect(resolve).exec()
		})
	}

	async function drawElement(ctx, selector, offsetX, offsetY) {
		const node = await getNodeInfo(selector)

		// 绘制背景
		if (node.backgroundColor && node.backgroundColor !== 'rgba(0, 0, 0, 0)') {
			ctx.setFillStyle(node.backgroundColor)
			ctx.fillRect(offsetX, offsetY, node.width, node.height)
		}

		// 处理子节点
		for (const child of node.children) {
			if (child.tagName === 'IMAGE') {
				await drawImage(ctx, child, offsetX, offsetY)
			} else if (child.text) {
				drawText(ctx, child, offsetX, offsetY)
			} else if (child.children) {
				await drawElement(ctx, child, offsetX + child.left, offsetY + child.top)
			}
		}
	}

	async function getNodeInfo(selector) {
		return new Promise((resolve) => {
			uni.createSelectorQuery()
				.in(instance)
				.select(selector)
				.fields(
					{
						node: true,
						rect: true,
						size: true,
						computedStyle: ['backgroundColor', 'color', 'fontSize', 'fontFamily'],
						dataset: true
					},
					resolve
				)
				.exec()
		})
	}

	async function drawImage(ctx, node, parentX, parentY) {
		const { tempFilePath } = await downloadFile(node.src)
		ctx.drawImage(tempFilePath, parentX + node.left, parentY + node.top, node.width, node.height)
	}

	function drawText(ctx, node, parentX, parentY) {
		ctx.setFontSize(node.fontSize)
		ctx.setFillStyle(node.color)
		ctx.setTextBaseline('middle')
		ctx.fillText(node.text, parentX + node.left, parentY + node.top + node.height / 2)
	}

	function downloadFile(url) {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: imageBaseUrl.value + url,
				success: resolve,
				fail: reject
			})
		})
	}

	async function checkPhotoPermission() {
		const { authSetting } = await uni.getSetting()
		if (!authSetting['scope.writePhotosAlbum']) {
			await uni.authorize({ scope: 'scope.writePhotosAlbum' })
		}
	}
</script>

<style>
	/* 原有样式保持 */
	.shareCare {
		width: 300px;
		background: #fff;
		border-radius: 8px;
		padding: 12px;
		box-sizing: border-box;
	}

	.careImg image {
		width: 100%;
		height: 150px;
	}

	.save-btn {
		margin-top: 20px;
		background: #07c160;
		color: white;
	}

	/* 添加文字截断样式 */
	.ellipsis {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
</style>
